package com.scsj.supermarket.view.activity.ordermodel;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.MineOrderDetailAdapter;
import com.scsj.supermarket.base.CancelMineOrderBase;
import com.scsj.supermarket.base.ConfirmOrderBase;
import com.scsj.supermarket.base.MineOrderDetailBase;
import com.scsj.supermarket.base.RefundOrderBase;
import com.scsj.supermarket.bean.CancelOrderBean;
import com.scsj.supermarket.bean.ConfirmOrderBean;
import com.scsj.supermarket.bean.MineOrderDetailBean;
import com.scsj.supermarket.bean.RefundOrderBean;
import com.scsj.supermarket.bean.TotalOrderBean;
import com.scsj.supermarket.presenter.CancelMineOrderPresenter;
import com.scsj.supermarket.presenter.ConfirmMineOrderPresenter;
import com.scsj.supermarket.presenter.MineOrderDetailPresenter;
import com.scsj.supermarket.presenter.RefundOrderPresenter;
import com.scsj.supermarket.utils.GoPayBackWindow;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;


/**
 * 订单详情
 */
public class OrderDetailActivity extends BaseActivity implements MineOrderDetailBase.IView,
        CancelMineOrderBase.IView, RefundOrderBase.IView, ConfirmOrderBase.IView {

    private MineOrderDetailPresenter mineOrderDetailPresenter;
    private CancelMineOrderPresenter cancelMineOrderPresenter;
    private ConfirmMineOrderPresenter confirmMineOrderPresenter;
    private RefundOrderPresenter refundOrderPresenter;
    private GoPayBackWindow goPayBackWindow;
    private RecyclerView order_detail_rv;
    private MineOrderDetailAdapter orderDetailAdapter;
    private RelativeLayout seeMoreItemRl, orderDetailBottomLay;
    private boolean isShowAllItem = false;
    private List twoList;
    private List<MineOrderDetailBean.DataBean.ShopOrderGoodsDetailsListBean> goodsDetailsListBeans;
    private TextView totalGoodsNum, orderDetailState, orderDetailStateDescription,
            orderDetailTopBtn, orderDetailLeftBtn, orderDetailRightBtn;
    private int orderStateNumber;
    private RelativeLayout baseView;
    private LinearLayout topLayout;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_detail_layout);
        orderStateNumber = getIntent().getIntExtra("order_state", -1);
        initToolbar();
        setToolbarTitle("订单详情");
        hasBack(true);
        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        mineOrderDetailPresenter = new MineOrderDetailPresenter(this);
        cancelMineOrderPresenter = new CancelMineOrderPresenter(this);
        confirmMineOrderPresenter = new ConfirmMineOrderPresenter(this);
        refundOrderPresenter = new RefundOrderPresenter(this);
        topLayout = findViewById(R.id.order_detail_top_info_ll);
        order_detail_rv = findViewById(R.id.order_detail_rv);
        order_detail_rv.setLayoutManager(new LinearLayoutManager(this));
        order_detail_rv.setNestedScrollingEnabled(false);

        seeMoreItemRl = findViewById(R.id.order_detail_totle_num_rl);
        totalGoodsNum = findViewById(R.id.order_detail_totle_num_tv);

        orderDetailState = findViewById(R.id.order_detail_state_tv);
        orderDetailStateDescription = findViewById(R.id.order_detail_state_description_tv);
        orderDetailTopBtn = findViewById(R.id.order_detail_state_top_tv);
        orderDetailLeftBtn = findViewById(R.id.order_detail_state_left_tv);
        orderDetailRightBtn = findViewById(R.id.order_detail_state_right_tv);
        baseView = findViewById(R.id.order_detail_ly);
        orderDetailBottomLay = findViewById(R.id.order_detail_bottom_lay);
        toSelectPage(orderStateNumber);
    }

    @Override
    protected void initListener() {
        seeMoreItemRl.setOnClickListener(new OrderDetailListener("see_more_order"));
        topLayout.setOnClickListener(new OrderDetailListener("top_layout"));
    }

    @Override
    protected void initData() {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderId", "dd18070435363009bb");
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        mineOrderDetailPresenter.deliverData(body);

    }

    //控制动画
    public void isShow(Boolean show) {
    }

    private void toSelectPage(int orderStateNumber) {

        switch (orderStateNumber) {
            case 0:
                //退款
                orderDetailState.setText("待确定");
                orderDetailStateDescription.setText("订单已退款¥16.22至您的微信账户");
                orderDetailTopBtn.setVisibility(View.VISIBLE);
                orderDetailBottomLay.setVisibility(View.GONE);
                orderDetailTopBtn.setText("查看退款");
                break;
            case 1:
                //待付款
                orderDetailState.setText("待付款");
                orderDetailStateDescription.setText("请在订单提交后尽快完成支付，超时订单将自动取消");
                orderDetailTopBtn.setVisibility(View.GONE);
                orderDetailBottomLay.setVisibility(View.VISIBLE);
                orderDetailLeftBtn.setText("取消订单");
                orderDetailLeftBtn.setOnClickListener(new OrderDetailListener("cancel_order"));
                orderDetailRightBtn.setText("立即支付");
                break;
            case 2:
                //待发货
                orderDetailState.setText("待发货");
                orderDetailStateDescription.setText("付款成功，等待商家确认订单");
                orderDetailTopBtn.setVisibility(View.VISIBLE);
                orderDetailBottomLay.setVisibility(View.GONE);
                orderDetailTopBtn.setText("申请退款");
                orderDetailTopBtn.setOnClickListener(new OrderDetailListener("refund_order"));
                break;
            case 3:
                //待收货
                orderDetailState.setText("待收货");
                orderDetailStateDescription.setText("配送员已取货，请您保持电话畅通，避免影响收货时间");
                orderDetailTopBtn.setVisibility(View.VISIBLE);
                orderDetailBottomLay.setVisibility(View.GONE);
                orderDetailTopBtn.setText("确认收货");
                orderDetailTopBtn.setOnClickListener(new OrderDetailListener("confirm_order"));
                break;
            case 4:
                //已完成
                orderDetailState.setText("已完成");
                orderDetailStateDescription.setText("您的订单已完成，欢迎下次光临");
                orderDetailTopBtn.setVisibility(View.GONE);
                orderDetailBottomLay.setVisibility(View.VISIBLE);
                orderDetailLeftBtn.setText("再来一单");
                orderDetailRightBtn.setText("立即评价");
                break;
        }
    }

    @Override
    public void showSuccessMsg(String s, MineOrderDetailBean mineOrderBean) {
        //获取我的订单详情成功
        Toasty.info(this, "店铺名称" + mineOrderBean.getData().getStoreName()).show();
        if (mineOrderBean != null && mineOrderBean.isSuccess()) {
            //给各个控件设置值
            //店铺名称
            TextView shopNameTv = findViewById(R.id.order_detail_shop_name_tv);
            String shopName = mineOrderBean.getData().getStoreName();
            shopNameTv.setText(shopName);

            //配送费
            TextView deliveryFeiTv= findViewById(R.id.order_detail_shipping_fee_tv);
            double deliveryFei= (double) mineOrderBean.getData().getDeliveryFee();
            deliveryFeiTv.setText(deliveryFei+"");

            //优惠券
            TextView discountAmountTv= findViewById(R.id.order_detail_discount_coupon_tv);
            double disCountStr= mineOrderBean.getData().getDiscountAmount();
            discountAmountTv.setText(disCountStr+"");

            //总重量
            TextView totalWeightTv= findViewById(R.id.order_detail_totle_weight_tv);
            Double totalWeight= mineOrderBean.getData().getWeightSum();
            totalWeightTv.setText(totalWeight+"");

            //购买件数
            int buyNum= mineOrderBean.getData().getShopOrderGoodsDetailsList().size();
            //优惠价格
            double disCountMonry= (double) mineOrderBean.getData().getDeliveryFee();
            TextView goodsNumAndDisCountAmount= findViewById(R.id.order_detail_num_money_tv);
            goodsNumAndDisCountAmount.setText("共"+buyNum+"件，已优惠"+disCountMonry+"元");

            //实付金额
            double storeMoney= mineOrderBean.getData().getOrderAmount();
            TextView buyPriceTv= findViewById(R.id.order_detail_total_price_tv);
            buyPriceTv.setText(storeMoney+"");

            //收货人名字
            String receiverName= mineOrderBean.getData().getReceiverName();
            //收货人电话
            String receiverPhone= mineOrderBean.getData().getReceiverPhone();
            TextView receiverNameAndTelTv= findViewById(R.id.order_detail_name_tel_tv);
            receiverNameAndTelTv.setText(receiverName+" "+receiverPhone);

            //收货人地址
            // String receiverAddress= mineOrderBean.getData().geta
            //配送方式
            TextView delieveryTypeTv= findViewById(R.id.order_detail_shipping_method_tv);
            int delieveryType= mineOrderBean.getData().getDeliveryBossType();
            if (1== delieveryType){
                delieveryTypeTv.setText("店家配送");
            }else if (2== delieveryType){
                delieveryTypeTv.setText("商圈配送");
            }

            //商品总件数
            TextView goodsTotalNumTv= findViewById(R.id.order_detail_totle_num_tv);
            goodsTotalNumTv.setText("共"+buyNum+"件");
            //订单号码
            String orderSn= mineOrderBean.getData().getOrderNum();
            TextView orderSnTv= findViewById(R.id.order_detail_order_number_tv);
            orderSnTv.setText(orderSn+"");

            //下单时间
            String creatOrderTime= mineOrderBean.getData().getCreateDate();
            TextView creatOrderTimeTv= findViewById(R.id.order_detail_order_time_tv);
            creatOrderTimeTv.setText(creatOrderTime);

            //支付方式
            String payMethod= (String) mineOrderBean.getData().getPaymentType();
            TextView payMethodTv= findViewById(R.id.order_detail_offer_method_tv);
            payMethodTv.setText(payMethod);

            //订单备注
            String orderNotes= mineOrderBean.getData().getBuyerNotes();
            TextView buyerNotesTv= findViewById(R.id.order_detail_more_tv);
            buyerNotesTv.setText(orderNotes);

            //列表相关设置
            goodsDetailsListBeans= mineOrderBean.getData().getShopOrderGoodsDetailsList();

            twoList = new ArrayList();
            twoList.add(goodsDetailsListBeans.get(0));
            twoList.add(goodsDetailsListBeans.get(1));

            orderDetailAdapter = new MineOrderDetailAdapter(twoList, this);
            order_detail_rv.setAdapter(orderDetailAdapter);


        }
    }

    @Override
    public void showSuccessMsg(String s, CancelOrderBean cancelOrderBean) {
        //取消订单成功
    }

    @Override
    public void showSuccessMsg(String s, RefundOrderBean refundOrderBean) {
        //退款成功
    }

    @Override
    public void showSuccessMsg(String s, ConfirmOrderBean confirmOrderBean) {
        //确认订单成功
    }

    @Override
    public void showErrorMsg(String s) {

    }

    /**
     * 相关点击事件处理
     */
    private class OrderDetailListener implements View.OnClickListener {
        private String clickType;
        public OrderDetailListener(String clickType) {
            this.clickType = clickType;
        }

        @Override
        public void onClick(View view) {
            switch (clickType) {
                case "see_more_order":
                    if (!isShowAllItem) {
                        //加载所有条目
                        orderDetailAdapter = new MineOrderDetailAdapter(goodsDetailsListBeans, OrderDetailActivity.this);
                        isShowAllItem = true;
                    } else {
                        //加载前两项
                        orderDetailAdapter = new MineOrderDetailAdapter(twoList, OrderDetailActivity.this);
                        isShowAllItem = false;
                    }
                    order_detail_rv.setAdapter(orderDetailAdapter);
                    break;

                case "cancel_order":
                    //取消订单
                    Toast.makeText(OrderDetailActivity.this, "点击取消", Toast.LENGTH_SHORT).show();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("orderId", "180521474964oken");
                    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                    cancelMineOrderPresenter.deliverData(body);
                    break;
                case "refund_order":
                    //申请退款

                    goPayBackWindow = new GoPayBackWindow(mContext, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            goPayBackWindow = new GoPayBackWindow(mContext, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    if (TextUtils.isEmpty(goPayBackWindow.getResion()) || goPayBackWindow.getResion().length() <= 1) {

                                        Toast.makeText(OrderDetailActivity.this, "请先填写或输入原因", Toast.LENGTH_SHORT).show();

                                    } else {
                                        JSONObject jsonObject1 = new JSONObject();
                                        jsonObject1.put("orderId", "180521474964oken");
                                        jsonObject1.put("refundReason", "buxiangyaole");
                                        RequestBody body1 = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString());
                                        refundOrderPresenter.deliverData(body1);
                                        goPayBackWindow.dismiss();
                                    }
                                }
                            });
                        }
                    });
                    goPayBackWindow.showAtLocation(baseView, Gravity.CENTER, 0, 0);
                    break;
                case "confirm_order":
                    //确认收货
                    Toast.makeText(OrderDetailActivity.this, "确认收货", Toast.LENGTH_SHORT).show();
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("orderId", "180521474964oken");
                    RequestBody body2 = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject2.toString());
                    confirmMineOrderPresenter.deliverData(body2);
                    break;
                case "top_layout":
                    //查看订单流程
                    Toast.makeText(OrderDetailActivity.this, "点了一下下", Toast.LENGTH_SHORT).show();
                    SkipUtils.toOrderProcessPage(OrderDetailActivity.this);
                    break;
            }
        }
    }
}
